//package com.xyh.transaction.listener;
//
//import com.xyh.transaction.entity.ChatMessage;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.event.EventListener;
//import org.springframework.messaging.simp.SimpMessageSendingOperations;
//import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
//import org.springframework.stereotype.Component;
//import org.springframework.web.socket.messaging.SessionConnectedEvent;
//import org.springframework.web.socket.messaging.SessionDisconnectEvent;
//
//import java.util.Queue;
//import java.util.concurrent.ConcurrentLinkedQueue;
//
//@Slf4j
//@Component
//public class WebSocketEventListener {
//
//
//    private final SimpMessageSendingOperations messagingTemplate;
//
//    private Queue<String> customerServiceQueue = new ConcurrentLinkedQueue<>();
//
//    public WebSocketEventListener(SimpMessageSendingOperations messagingTemplate) {
//        this.messagingTemplate = messagingTemplate;
//
//        // 初始化队列并添加客服代表
//        this.customerServiceQueue = new ConcurrentLinkedQueue<>();
//        customerServiceQueue.offer("CustomerService1");
//        customerServiceQueue.offer("CustomerService2");
//        // 更多客服可以被添加
//    }
//
//
//    @EventListener
//    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
//        log.info("Received a new web socket connection");
//        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
//        String sessionId = headerAccessor.getSessionId();
//
//        // 分配客服
//        String customerService = customerServiceQueue.poll();
//        if (customerService != null) {
//            // 发送默认消息给用户
//            messagingTemplate.convertAndSendToUser(sessionId, "/topic/default", "您已连接到客服 " + customerService + "，请问有什么可以帮您？");
//
//            // 分配完的客服重新加入队列
//            customerServiceQueue.offer(customerService);
//        } else {
//            // 如果没有客服可用，发送相应的提示
//            messagingTemplate.convertAndSendToUser(sessionId, "/topic/default", "当前客服忙碌，请稍后再试。");
//        }
//    }
//
//    @EventListener
//    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
//        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
//
//        String username = (String) headerAccessor.getSessionAttributes().get("username");
//        if (username != null) {
//            log.info("User Disconnected : " + username);
//
//            ChatMessage chatMessage = new ChatMessage();
//            chatMessage.setType(ChatMessage.MessageType.LEAVE);
//            chatMessage.setSender(username);
//
//            messagingTemplate.convertAndSend("/topic/public", chatMessage);
//        }
//    }
//}
